//
//  LXHomeViewController.m
//  bgms_d
//
//  Created by Mountain on 20/2/2019.
//  Copyright © 2019 lachesis-zhu. All rights reserved.
//

#import "LXHomeViewController.h"
#import "LXDevSettingViewController.h"
#import "LXAlertTableViewController.h"
#import "LXConnectViewController.h"
#import "LXFoodViewController.h"
#import "LXMoreViewController.h"
#import "LXTimeScrollerVC.h"
#import "LXLineViewController.h"
#import "BLETransDeviceSingleton.h"
#import "LXHomeTableViewCell.h"
#import "LXAlertView.h"
#import "LXAlertModel.h"
#import "DataModal.h"
#import "LXLocalNotification.h"

@interface LXHomeViewController () <LXHomeTableViewCellDelegate, BLETransDeviceSingletonDelegate, LXAlertViewDelegate>
{
    BLETransDeviceSingleton *ble;
    LXFoodItem *selectItem;
    NSInteger timeIndex;
    LXDevSettingModel *devSetting;
    BOOL hadAcceptData;
    BOOL blueToothDisconnect;
}
@property (nonatomic, strong) NSMutableArray *levelArray;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) LXLineViewController *lineVC;
@property (nonatomic, strong) NSMutableDictionary *showDataDic;
@property (nonatomic, strong) NSMutableArray *alertsArray;
@property (nonatomic, strong) LXLocalNotification *localNoti;

@end

@implementation LXHomeViewController

#pragma mark -  public method
- (void)sendSettingData:(LXFoodItem *)sendItem {
    NSMutableData *sendData = [[NSMutableData alloc] init];
    for (NSInteger i = 0; i < 6; i ++) {
        LXFoodItem *item = [self.tempsArray objectAtIndex:i];
        if (i == sendItem.placeNum) {
            NSInteger tempNum = [sendItem.setNum integerValue];
            UInt8 MessageBt[2];
            MessageBt[0] = tempNum >> 8 & 0xff;
            MessageBt[1] = tempNum & 0xff;
            NSData *content = [NSData dataWithBytes:MessageBt length:2];
            [sendData appendData:content];
        } else {
            NSInteger tempNum = [item.setNum integerValue];
            UInt8 MessageBt[2];
            MessageBt[0] = tempNum >> 8 & 0xff;
            MessageBt[1] = tempNum & 0xff;
            NSData *content = [NSData dataWithBytes:MessageBt length:2];
            [sendData appendData:content];
        }
    }
    Byte *dataByte = (Byte *)[sendData bytes];
    [[BLETransDeviceSingleton sharedInstance] characteristc:SET_CHARACTERISTIC_UUID sendHostCmd:dataByte lenght:12];
    [self performSelector:@selector(placeNumSend:) withObject:sendItem afterDelay:2];
}

#pragma mark -  life cycle
- (void)dealloc
{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializationData];
    [self addNotification];
    
    [self loadUI];
    
    [self loadViewDatas];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    if (self.foodItem && self.foodItem.setNum) {
        if ([self.foodItem.setNum isEqualToString:@""]) {
            selectItem.setNum = @"";
            selectItem.minNum = @"";
            selectItem.alertNum = 0;
        } else {
            self.foodItem.placeNum = selectItem.placeNum;
            selectItem = self.foodItem;
            selectItem.alertNum = 0;
        }
        [self.showArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            LXFoodItem *item = obj;
            if (item.placeNum == selectItem.placeNum) {
                selectItem.tempNum = item.tempNum;
                [self.showArray replaceObjectAtIndex:idx withObject:selectItem];
                LXHomeTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
                cell.timeDisable = NO;
                [self showCell:cell withItem:selectItem];
                *stop = YES;
            }
        }];
        [self.tempsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            LXFoodItem *item = obj;
            if (item.placeNum == selectItem.placeNum) {
                [self.tempsArray replaceObjectAtIndex:idx withObject:selectItem];
                *stop = YES;
            }
        }];
        self.foodItem = [LXFoodItem new];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

#pragma mark -  over write

#pragma mark -  setter & getter

#pragma mark -  private method
- (void)initializationData
{
    ble = [BLETransDeviceSingleton sharedInstance];
    ble.delegate = self;
    self.localNoti = [[LXLocalNotification alloc] init];
    
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (int i = 0; i < 6; i ++) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [array addObject:dic];
    }
    [self saveObject:array forKey:@"alertData"];
    
    NSDictionary *dic = [self getObjectForKey:@"DevSetting"];
    devSetting = [LXDevSettingModel shareSettingModel];
    devSetting.tempUnitF = [dic[@"tempUnitF"] boolValue];
    devSetting.connectNotif = [dic[@"connectNotif"] boolValue];
    devSetting.alertInterval = dic[@"alertInterval"] ? dic[@"alertInterval"] : [NSString stringWithFormat:@"5 %@", NSLocalizedString(@"Minute", nil)];
    devSetting.alertRingtone = dic[@"alertRingtone"] ? [dic[@"alertRingtone"] boolValue] : YES;
    devSetting.alertVibration = dic[@"alertVibration"] ? [dic[@"alertVibration"] boolValue] : YES;
}

- (void)loadUI
{
    self.view.backgroundColor = kAppBackgroundColor;
    [self buildNavi];
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXHomeTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"cell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(devSetting:)];
    gesture.numberOfTapsRequired = 1;
    gesture.numberOfTouchesRequired = 1;
    [self.devSettingView addGestureRecognizer:gesture];
    
    [self.wifiButton setImage:[UIImage imageNamed:@"信号连接"] forState:UIControlStateSelected];
    [self.wifiButton setImage:[UIImage imageNamed:@"信号未连接"] forState:UIControlStateNormal];
    self.wifiButton.selected = NO;
}

- (void)loadViewDatas
{
    
}

- (void)buildNavi
{
    [self.navigationView drawAroundViewWithLocation:DrawBottom color:kAppLinesColor insets:UIEdgeInsetsMake(-0.5, 0, 0, 0)];
    if (IPHONE_X) {
        self.naviHeight.constant = 66 + 22;
    }
    /*UILabel *labelName = [[UILabel alloc] init];
    labelName.textColor = kAppNormalTextColor;
    labelName.font = [UIFont lx_systemFontOfSize:17];
    labelName.text = @"Home";
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc] initWithCustomView:labelName];
    self.navigationItem.leftBarButtonItem = leftBar;
    
    UIButton *detailBtn = [[UIButton alloc] init];
    [detailBtn setImage:[UIImage imageNamed:@"更多"] forState:UIControlStateNormal];
    [detailBtn addTarget:self action:@selector(detailDown:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *detailBar = [[UIBarButtonItem alloc] initWithCustomView:detailBtn];
    UIButton *homeBtn = [[UIButton alloc] init];
    [homeBtn setImage:[UIImage imageNamed:@"温度查看"] forState:UIControlStateNormal];
    [homeBtn addTarget:self action:@selector(homeDown:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *homeBar = [[UIBarButtonItem alloc] initWithCustomView:homeBtn];
    self.navigationItem.rightBarButtonItems = @[homeBar, detailBar];*/
}

- (NSData *)formateBitPlace:(NSInteger)data {
    UInt8 dataArray[8];
    for (NSInteger i = 0; i < 8; i++) {
        dataArray[i] = (data >> i) & 0x01;
    }
    return [NSData dataWithBytes:dataArray length:8];
}

- (void)notNotication:(NSNotification *)notification
{
    NSData *data = notification.userInfo[kAppHeadUnitData];
    Byte *MessageBt = (Byte *)[data bytes];
    NSInteger tempValue = MessageBt[0];
    self.battleLabel.text = [NSString stringWithFormat:@"%ld%@", (long)tempValue, @"%"];
    if (tempValue <= 33) {
        self.bettyImageView.image = [UIImage imageNamed:@"电池-1"];
    } else if (tempValue > 33 && tempValue <= 66) {
        self.bettyImageView.image = [UIImage imageNamed:@"电池-2"];
    } else {
        self.bettyImageView.image = [UIImage imageNamed:@"电池-3"];
    }
    self.wifiButton.selected = YES;
    
    NSInteger clickDown = MessageBt[2];
    NSData *placeData = [self formateBitPlace:MessageBt[1]];
    Byte *placeByte = (Byte *)[placeData bytes];
    if (clickDown == 1) {
        [self.alertsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            LXAlertView *alert = obj;
            if (alert.tag >= 10) {
                [alert alertHidden];
                [self.alertsArray removeObject:alert];
                [self.localNoti removeOneNotificationWithID:[NSString stringWithFormat:@"%ld", [alert.placeNum integerValue] + 10]];
                *stop = YES;
            }
        }];
        [self.showArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
            LXHomeTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            cell.timeProgress = 0;
            LXFoodItem *item = obj;
            item.alertNum = 0;
        }];
    } else {
        [self.showArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            LXFoodItem *item = obj;
            NSInteger index = item.placeNum;
            NSInteger place = placeByte[index];
            if (place != 0) {
                __block BOOL hadShow = NO;
                [self.alertsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    LXAlertView *view = obj;
                    if (view.tag - 10 == item.placeNum) {
                        hadShow = YES;
                        *stop = YES;
                    }
                }];
                if (!hadShow) {
                    [self gotoBlueView:item withIndex:idx];
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
                    LXHomeTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                    cell.timeProgress = 1;
                }
            }
        }];
    }
}

- (void)alertViewNotification:(NSNotification *)notification {
    NSDictionary *userInfo = [notification object];
    NSInteger place = [userInfo[@"placeNum"] integerValue];
    NSString *type = userInfo[@"type"];
    if ([type isEqualToString:@"1"]) {
        NSMutableArray *alertsArray = [[NSMutableArray alloc] initWithArray:[self getObjectForKey:@"alertData"]];
        [alertsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:obj];
            if ([dic[@"placeNum"] integerValue] == place) {
                [dic setObject:@"NO" forKey:@"alert"];
            }
            [alertsArray replaceObjectAtIndex:idx withObject:dic];
        }];
        [self saveObject:alertsArray forKey:@"alertData"];
    } else if ([type isEqualToString:@"0"]) {
        [self.alertsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            LXAlertView *view = obj;
            if ([view.placeNum integerValue] == place) {
                [view alertHidden];
                [self.alertsArray removeObject:view];
                [[BLETransDeviceSingleton sharedInstance] secretKeySendTimeAlert:[[LXDevSettingModel shareSettingModel].alertInterval integerValue] boundsAlert:[view.placeNum integerValue] alertOn:NO];
            }
        }];
    }
    
    LXAlertTableViewController *vc = [[LXAlertTableViewController alloc] initWithNibName:@"LXAlertTableViewController" bundle:nil];
    vc.tempArray = self.showArray;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)temNotication:(NSNotification *)notification
{
    self.wifiButton.selected = YES;
    hadAcceptData = YES;
    NSData *data = notification.userInfo[kAppHeadUnitData];
    Byte *MessageBt = (Byte *)[data bytes];
    NSInteger devTemp1 = MessageBt[0] * 256 + MessageBt[1];
    NSString *devString1 = @"";
    devString1 = [NSString stringWithFormat:@"%ld", (long)devTemp1];
    LXFoodItem *item1 = [self.tempsArray objectAtIndex:0];
    item1.tempNum = devString1;
    [self.tempsArray replaceObjectAtIndex:0 withObject:item1];
    NSInteger devTemp2 = MessageBt[2] * 256 + MessageBt[3];
    NSString *devString2 = @"";
    devString2 = [NSString stringWithFormat:@"%ld", (long)devTemp2];
    LXFoodItem *item2 = [self.tempsArray objectAtIndex:1];
    item2.tempNum = devString2;
    [self.tempsArray replaceObjectAtIndex:1 withObject:item2];
    NSInteger devTemp3 = MessageBt[4] * 256 + MessageBt[5];
    NSString *devString3 = @"";
    devString3 = [NSString stringWithFormat:@"%ld", (long)devTemp3];
    LXFoodItem *item3 = [self.tempsArray objectAtIndex:2];
    item3.tempNum = devString3;
    [self.tempsArray replaceObjectAtIndex:2 withObject:item3];
    NSInteger devTemp4 = MessageBt[6] * 256 + MessageBt[7];
    NSString *devString4 = @"";
    devString4 = [NSString stringWithFormat:@"%ld", (long)devTemp4];
    LXFoodItem *item4 = [self.tempsArray objectAtIndex:3];
    item4.tempNum = devString4;
    [self.tempsArray replaceObjectAtIndex:3 withObject:item4];
    NSInteger devTemp5 = MessageBt[8] * 256 + MessageBt[9];
    NSString *devString5 = @"";
    devString5 = [NSString stringWithFormat:@"%ld", (long)devTemp5];
    LXFoodItem *item5 = [self.tempsArray objectAtIndex:4];
    item5.tempNum = devString5;
    [self.tempsArray replaceObjectAtIndex:4 withObject:item5];
    NSInteger devTemp6 = MessageBt[10] * 256 + MessageBt[11];
    NSString *devString6 = @"";
    devString6 = [NSString stringWithFormat:@"%ld", (long)devTemp6];
    LXFoodItem *item6 = [self.tempsArray objectAtIndex:5];
    item6.tempNum = devString6;
    [self.tempsArray replaceObjectAtIndex:5 withObject:item6];
    
    [self dataArrangement];
}

- (void)dataArrangement {
    NSMutableArray *array1 = [[NSMutableArray alloc] init];
    NSMutableArray *array2 = [[NSMutableArray alloc] init];
    [self.tempsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        LXFoodItem *item = obj;
        if ([item.tempNum integerValue] > 0 && [item.tempNum integerValue] < 600) {
            [array1 addObject:item];
        } else {
            [array2 addObject:item];
        }
    }];
    [array1 addObjectsFromArray:array2];
    self.showArray = [[NSMutableArray alloc] initWithArray:array1];
    
    NSArray *cells = [self.tableView visibleCells];
    [cells enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        LXHomeTableViewCell *cell = obj;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        LXFoodItem *item = [self.showArray objectAtIndex:indexPath.row];
        [self showCell:cell withItem:item];
    }];
    
    [self checkAlertView];
    
    NSArray *keys = [self.showDataDic allKeys];
    __block BOOL hadCutDown = NO;
    [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *key = obj;
        if (![key isEqualToString:@"startDate"]) {
            NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:[self.showDataDic objectForKey:key]];
            NSInteger index = [key integerValue];
            if (tempArray.count >= 300) {
                NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(0, 60)];
                [tempArray removeObjectsAtIndexes:indexSet];
                hadCutDown = YES;
            }
            if (index <= self.tempsArray.count - 1) {
                LXFoodItem *newItem = self.tempsArray[index];
                [tempArray addObject:newItem.tempNum];
            }
            [self.showDataDic setObject:tempArray forKey:key];
        }
    }];
    NSString *startDate = [self.showDataDic valueForKey:@"startDate"];
    if (!startDate || [startDate isEqualToString:@""]) {
        NSDateFormatter *formate = [[NSDateFormatter alloc] init];
        [formate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        [self.showDataDic setValue:[formate stringFromDate:[NSDate new]] forKey:@"startDate"];
        hadCutDown = YES;
    }
    if (hadCutDown) {
        NSDateFormatter *formate = [[NSDateFormatter alloc] init];
        [formate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *startDate = [self.showDataDic valueForKey:@"startDate"];
        NSDate *lastDate = [formate dateFromString:startDate];
        NSDate *newDate = [NSDate dateWithTimeInterval:60 sinceDate:lastDate];
        [self.showDataDic setValue:[formate stringFromDate:newDate] forKey:@"startDate"];
    }
    if (self.lineVC) {
        self.lineVC.showDataDic = self.showDataDic;
        [self.lineVC refreshLineDat:self.tempsArray hasCut:hadCutDown];
    }
}

- (void)checkData {
    for (NSInteger i = 0; i < 6; i ++) {
        LXFoodItem *item = [self.tempsArray objectAtIndex:i];
        item.tempNum = [NSString stringWithFormat:@"%u", arc4random() % 150 + 100];
        [self.tempsArray replaceObjectAtIndex:i withObject:item];
    }
    [self dataArrangement];
}

- (void)checkAlertView {
    NSMutableArray *alertsArray = [[NSMutableArray alloc] initWithArray:[self getObjectForKey:@"alertData"]];
    NSDateFormatter *formate = [[NSDateFormatter alloc] init];
    [formate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [alertsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:obj];
        if ([dic[@"alert"] isEqualToString:@"YES"]) {
            NSDate *alertDate = [formate dateFromString:dic[@"alertTime"]];
            NSComparisonResult result = [alertDate compare:[NSDate new]];
            if (result == NSOrderedSame || result == NSOrderedAscending) {
                NSString *tempString = [[NSUserDefaults standardUserDefaults] getObjectForKey:AppInBackground];
                if (![tempString isEqualToString:@"YES"]) {
                    [self.localNoti removeOneNotificationWithID:[NSString stringWithFormat:@"%ld", self.foodItem.placeNum]];
                }
                [self showAlertView:dic with:idx atShowData:NO];
                [dic setObject:@"NO" forKey:@"alert"];
                [alertsArray replaceObjectAtIndex:idx withObject:dic];
                [self refreshIndex:idx withDic:dic showAll:YES];
            } else {
                [self refreshIndex:idx withDic:dic showAll:NO];
            }
        } else {
            [self refreshIndex:idx withDic:dic showAll:NO];
        }
    }];
    [self saveObject:alertsArray forKey:@"alertData"];
    
//    [self.showArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        LXFoodItem *item = obj;
//        if (![item.setNum isEqualToString:@""] && item.setNum != nil && [item.tempNum integerValue] < 600) {
//            NSDate *lastAlertDate = item.lastAlertDate;
//            if (!lastAlertDate) {
//                lastAlertDate = [NSDate new];
//                [self gotoBlueView:item withIndex:idx];
//            } else {
//                NSComparisonResult result = [[NSDate new] compare:lastAlertDate];
//                if (result == NSOrderedDescending) {
//                    [self gotoBlueView:item withIndex:idx];
//                } else {
//                    [self gotoHideBlueView:item withIndex:idx];
//                }
//            }
//        } else if ([item.setNum isEqualToString:@""]) {
//            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
//            LXHomeTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
//            cell.timeProgress = 0;
//        }
//    }];
}

- (void)gotoBlueView:(LXFoodItem *)item withIndex:(NSInteger)idx {
    NSDictionary *dic = @{@"placeNum" : [NSString stringWithFormat:@"%ld", item.placeNum],
                          @"alert" : @"NO",
                          @"titleString" : NSLocalizedString(@"TemperatureEnded", nil),
                          @"name" : [NSString stringWithFormat:@"%@#%ld %@:%@", NSLocalizedString(@"Probe", nil), item.placeNum + 1, NSLocalizedString(@"Temperature", nil), [[LXDevSettingModel shareSettingModel] tempCTempF:item.setNum]]};
    if (item.alertNum < 1) {
        item.alertNum += 1;
        NSString *tempString = [[NSUserDefaults standardUserDefaults] getObjectForKey:AppInBackground];
        NSDictionary *devDic = [self getObjectForKey:@"DevSetting"];
        BOOL notifBool = [devDic[@"connectNotif"] boolValue];
        if ([tempString isEqualToString:@"YES"]) {
            if (notifBool) {
                NSDate *newDate = [[NSDate new] dateByAddingTimeInterval:2];
                [self.localNoti addLocalNoticeTitle:dic[@"name"] alertBody:dic[@"titleString"] time:newDate withPlace:[NSString stringWithFormat:@"%ld", (long)item.placeNum] type:@"0"];
            }
        } else {
            [self showAlertView:dic with:idx atShowData:YES];
        }
        [self.showArray replaceObjectAtIndex:idx withObject:item];
    }
}

- (void)showAlertView:(NSDictionary *)dic with:(NSInteger)index atShowData:(BOOL)showData
{
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([LXAlertView class]) owner:nil options:nil];
    LXAlertView *alertView = [array firstObject];
    alertView.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:alertView];
    LXFoodItem *item;
    if (showData) { //temp
        item = [self.showArray objectAtIndex:index];
        alertView.tag = item.placeNum + 10;
    } else { //time
        item = [self.tempsArray objectAtIndex:index];
        alertView.tag = item.placeNum;
    }
    [self.alertsArray addObject:alertView];
    [UIView animateWithDuration:1 animations:^{
        alertView.frame = [UIApplication sharedApplication].keyWindow.bounds;
        alertView.valueLabel.text = [NSString stringWithFormat:@"%ld", (long)item.placeNum + 1];
        alertView.titleLabel1.text = dic[@"name"];
        alertView.titleLable2.text = showData ? dic[@"titleString"] : NSLocalizedString(@"TheTimerEnded", nil);
        alertView.detailLabel.text = showData ? @"" : dic[@"titleString"];
        NSString *timeString = [dic[@"alertTime"] substringWithRange:NSMakeRange(11, 5)];
        alertView.placeNum = dic[@"placeNum"] ? dic[@"placeNum"] : @"0";
        alertView.timeLabel.text = timeString ? timeString : dic[@"alertTime"];
    }];
    [alertView alertSounds];
}

- (void)gotoHideBlueView:(LXFoodItem *)item withIndex:(NSInteger)idx{
    if ([item.tempNum integerValue] < [item.setNum integerValue]) {
        [self.alertsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            LXAlertView *view = obj;
            if ([view.placeNum integerValue] == item.placeNum) {
                [view alertHidden];
                [self.alertsArray removeObject:view];
                [[BLETransDeviceSingleton sharedInstance] secretKeySendTimeAlert:[[LXDevSettingModel shareSettingModel].alertInterval integerValue] boundsAlert:[view.placeNum integerValue] alertOn:NO];
            }
        }];
    }
}

- (void)bleOperation {
    if (!ble) {
        ble = [BLETransDeviceSingleton sharedInstance];
        ble.delegate = self;
    }
    [ble operation];
}

- (void)appEnterBackground {
    for (NSInteger i = 0; i < 6; i ++) {
        LXFoodItem *item = [self.tempsArray objectAtIndex:i];
        item.tempNum = @"0";
        [self.tempsArray replaceObjectAtIndex:i withObject:item];
    }
    NSArray *keys = [self.showDataDic allKeys];
    [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *key = obj;
        if (![key isEqualToString:@"startDate"]) {
            NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:[self.showDataDic objectForKey:key]];
            [tempArray removeAllObjects];
            [self.showDataDic setObject:tempArray forKey:key];
        }
    }];
    [self.showDataDic setObject:@"" forKey:@"startDate"];
    if (self.lineVC) {
        self.lineVC.showDataDic = self.showDataDic;
        [self.lineVC refreshLineDat:self.tempsArray hasCut:YES];
    }
}

- (void)placeNumSend:(LXFoodItem *)sendItem {
    [[BLETransDeviceSingleton sharedInstance] secretKeySendTimeAlert:[[LXDevSettingModel shareSettingModel].alertInterval integerValue] boundsAlert:sendItem.placeNum alertOn:YES];
}

- (void)checkBlueTooth {
    [ble reConnect];
}
#pragma mark -  notification
- (void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notNotication:) name:NOT_CHARACTERISTIC_UUID object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(temNotication:) name:TEM_CHARACTERISTIC_UUID object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertViewNotification:) name:AlertViewNoti object:nil];
    
    [self.localNoti checkUserNotificationEnable];
}

#pragma mark -  network


#pragma mark -  event handle
- (IBAction)detailDown:(UIButton *)sender
{
    LXMoreViewController *vc = [[LXMoreViewController alloc] initWithNibName:NSStringFromClass([LXMoreViewController class]) bundle:nil];
    vc.tempArray = self.showArray;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)homeDown:(UIButton *)sender
{
    self.lineVC = [[LXLineViewController alloc] initWithNibName:NSStringFromClass([LXLineViewController class]) bundle:nil];
    self.lineVC.tempArray = self.tempsArray;
    self.lineVC.showDataDic = self.showDataDic;
    [self.navigationController pushViewController:self.lineVC animated:YES];
}

- (IBAction)bleRefresh:(UIButton *)sender {
    if (!sender.isSelected) {
        [self bleOperation];
    }
}

- (void)devSetting:(UIGestureRecognizer *)gesture
{
    LXDevSettingViewController *vc = [[LXDevSettingViewController alloc] initWithNibName:NSStringFromClass([LXDevSettingViewController class]) bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)showCell:(LXHomeTableViewCell *)cell withItem:(LXFoodItem *)item
{
    cell.levelLable.text = [NSString stringWithFormat:@"%ld", item.placeNum + 1];
    cell.levelImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"type%ld", item.placeNum + 1]];
    if ([item.tempNum integerValue] > 600 || [item.tempNum isEqualToString:@"0"] || !item.tempNum) {
        cell.nowTempLabel.textColor = kAppLowTextColor;
        cell.nowTempLabel.text = @"----";
        cell.timeProgress = 0;
        cell.timeDisable = YES;
    } else {
        cell.nowTempLabel.textColor = kAppThemeColor;
        cell.nowTempLabel.text = [[LXDevSettingModel shareSettingModel] tempCTempF:item.tempNum];
        cell.timeDisable = NO;
    }
    if (!item.setNum || [item.setNum isEqualToString:@""]) {
        cell.typeImage.hidden = YES;
        cell.typeNameLabel.text = NSLocalizedString(@"NoPreset", nil);
        cell.settingLabel.text = @"-";
        cell.tempMusImage.hidden = YES;
        cell.tempMusLabel.hidden = YES;
    } else {
        cell.typeImage.hidden = NO;
        cell.typeImage.image = [UIImage imageNamed:item.image];
        NSString *detailString = [NSString stringWithFormat:@"%@ %@",  item.name, [self.levelArray objectAtIndex:[item.cookedLevel integerValue]]];
        cell.typeNameLabel.text = detailString;
        cell.settingLabel.text = [[LXDevSettingModel shareSettingModel] tempCTempF:item.setNum];
        if (item.rangeTemp) {
            cell.tempMusImage.hidden = NO;
            cell.tempMusLabel.hidden = NO;
            cell.tempMusLabel.text = [[LXDevSettingModel shareSettingModel] tempCTempF:item.minNum];
        } else {
            cell.tempMusImage.hidden = YES;
            cell.tempMusLabel.hidden = YES;
        }
    }
    if (item.setNum && ![item.setNum isEqualToString:@""]) {
        CGFloat rangeFloat = [item.setNum floatValue];
        CGFloat percent = [item.tempNum floatValue] / rangeFloat;
        cell.timeProgress = percent > 1 ? 1 : percent;
    }
}

- (void)refreshIndex:(NSInteger)index withDic:(NSDictionary *)dic showAll:(BOOL)show
{
    __block LXHomeTableViewCell *cell;
    [self.showArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        LXFoodItem *item = obj;
        if (item.placeNum == index) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
            cell = [self.tableView cellForRowAtIndexPath:indexPath];
            *stop = YES;
        }
    }];
    if (cell) {
        if (show) {
            cell.tempProgress = 1;
        } else {
            if ([dic[@"alert"] isEqualToString:@"NO"] || !dic) {
                cell.tempProgress = 0;
                return;
            }
            NSDateFormatter *formate = [[NSDateFormatter alloc] init];
            [formate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDate *endDate = [formate dateFromString:dic[@"alertTime"]];
            NSTimeInterval timeInterval = [endDate timeIntervalSinceDate:[NSDate new]];
            NSTimeInterval setInterval = [dic[@"minite"] integerValue] * 60 + [dic[@"second"] integerValue];
            CGFloat progross = (setInterval - timeInterval) / setInterval;
            cell.tempProgress = progross;
        }
    }
}
#pragma mark -  delegate
#pragma mark
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 154;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.showArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LXFoodItem *item = [self.showArray objectAtIndex:indexPath.row];
    LXHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.delegate = self;
    [cell clearHistory];
    [self showCell:cell withItem:item];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark - LXHomeTableViewCellDelegate
- (void)homeTableViewCell:(LXHomeTableViewCell *)cell btnDown:(UIView *)btn
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    LXFoodItem *item = [self.showArray objectAtIndex:indexPath.row];
    if (btn.tag == 0) {
        LXTimeScrollerVC *vc = [[LXTimeScrollerVC alloc] initWithNibName:NSStringFromClass([LXTimeScrollerVC class]) bundle:nil];
        vc.selectIndex = indexPath.row;
        LXFoodItem *item = [self.showArray objectAtIndex:indexPath.row];
        vc.foodItem = item;
        [self.navigationController pushViewController:vc animated:YES];
        timeIndex = indexPath.row;
    } else {
        LXFoodViewController *foodVC = [[LXFoodViewController alloc] initWithNibName:NSStringFromClass([LXFoodViewController class]) bundle:nil];
        [self.navigationController pushViewController:foodVC animated:YES];
        foodVC.tempItem = item;
        foodVC.devIndex = indexPath.row;
        selectItem = item;
    }
}

#pragma mark - BLETransDeviceSingletonDelegate
- (void)BLETransDeviceSingletonConnected:(BOOL)connected
{
    if (connected) {
        self.wifiButton.selected = YES;
        if (self.timer && [self.timer isValid]) {
            [self.timer invalidate];
        }
    } else {
        self.battleLabel.text = @"~%";
        self.bettyImageView.image = [UIImage imageNamed:@"未连接"];
        self.wifiButton.selected = NO;
    }
}

- (void)BLETransDeviceSingletonDisConnected:(BOOL)connected
{
    if (connected) {
        self.battleLabel.text = @"~%";
        self.bettyImageView.image = [UIImage imageNamed:@"未连接"];
        self.wifiButton.selected = NO;
        self.timer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(checkBlueTooth) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
        NSDictionary *devDic = [self getObjectForKey:@"DevSetting"];
        BOOL notifBool = [devDic[@"connectNotif"] boolValue];
        if (notifBool) {
            NSDate *newDate = [[NSDate new] dateByAddingTimeInterval:2];
            [self.localNoti addLocalNoticeTitle:@"" alertBody:NSLocalizedString(@"TheBlueToothDisconected", nil) time:newDate withPlace:@"" type:@""];
        }
    } else {
        self.wifiButton.selected = YES;
    }
}

- (void)BLETransDeviceSingletonBlueTooch:(BOOL)open {
    
}


- (void)BLETransDeviceSingletonSendReady:(BOOL)ready {
    
}


#pragma mark - LXAlertViewDelegate
- (void)alertView:(LXAlertView *)alertView okDown:(UIButton *)sender
{
    NSInteger index = alertView.tag;
    if (alertView.tag >= 10) {
        index = alertView.tag - 10;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        LXHomeTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.timeProgress = 0;
        cell.timeDisable = YES;
        [self.alertsArray removeObject:alertView];
        if (self.alertsArray.count == 0) {
            [[BLETransDeviceSingleton sharedInstance] secretKeySendTimeAlert:[[LXDevSettingModel shareSettingModel].alertInterval integerValue] boundsAlert:[alertView.placeNum integerValue] alertOn:NO];
            [self.showArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                LXFoodItem *item = obj;
                item.alertNum = 0;
            }];
        }
    } else {
        NSMutableArray *alertsArray = [[NSMutableArray alloc] initWithArray:[self getObjectForKey:@"alertData"]];
        NSDictionary *getDic = [alertsArray objectAtIndex:index];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:getDic];
        [dic setObject:@"NO" forKey:@"alert"];
        [dic setObject:@"YES" forKey:@"setting"];
        [alertsArray replaceObjectAtIndex:index withObject:dic];
        [self saveObject:alertsArray forKey:@"alertData"];
        [self refreshIndex:index withDic:dic showAll:NO];
    }
}

- (void)alertView:(LXAlertView *)alertView alertDown:(UIButton *)sender
{
    LXAlertTableViewController *vc = [[LXAlertTableViewController alloc] initWithNibName:NSStringFromClass([LXAlertTableViewController class]) bundle:nil];
    vc.tempArray = self.showArray;
    [self.navigationController pushViewController:vc animated:YES];
    
}
#pragma mark -  lazy load
- (NSMutableArray *)tempsArray {
    if (!_tempsArray) {
        _tempsArray = [[NSMutableArray alloc] init];
        for (NSInteger i = 0; i < 6; i ++) {
            LXFoodItem *item = [[LXFoodItem alloc] init];
            item.placeNum = i;
            item.alertNum = 0;
            [_tempsArray addObject:item];
        }
    }
    return _tempsArray;
}

- (NSMutableArray *)showArray {
    if (!_showArray) {
        _showArray = [[NSMutableArray alloc] initWithArray:self.tempsArray];
    }
    return _showArray;
}

- (NSMutableArray *)levelArray {
    if (!_levelArray) {
        _levelArray = [[NSMutableArray alloc] initWithObjects:NSLocalizedString(@"Rare", nil), NSLocalizedString(@"M.Rare", nil), NSLocalizedString(@"Medium", nil), NSLocalizedString(@"M.Well", nil), NSLocalizedString(@"WellDone", nil), NSLocalizedString(@"Done", nil), @"",  nil];
    }
    return _levelArray;
}

- (NSMutableDictionary *)showDataDic
{
    if (!_showDataDic) {
        _showDataDic = [[NSMutableDictionary alloc] init];
        for (NSInteger i = 0; i < 6; i ++) {
            [_showDataDic setObject:[NSMutableArray array] forKey:[NSString stringWithFormat:@"%ld", (long)i]];
        }
    }
    return _showDataDic;
}

- (NSMutableArray *)alertsArray {
    if (!_alertsArray) {
        _alertsArray = [[NSMutableArray alloc] init];
    }
    return _alertsArray;
}
#pragma mark -  memoryWarning

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
